package com.tsd.aspect;

import com.tsd.core.annotation.DataPermission;
import com.tsd.core.constants.Constants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.system.entity.SysDataAuthExt;
import com.tsd.system.entity.SysUserExt;
import com.tsd.utils.DataPermissionUtil;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @ClassName: CheckBindAspect
 * @Description: TODO
 * @Author: admin
 * @Date: 2022/11/14 11:30
 * @Version: 1.0
 */
@Order(1)
@Aspect
@Component
public class DataPermissionAspect {

    @Before("@annotation(permission)")
    public void beforeCheckBind(DataPermission permission) {
        if (HlpUtils.isEmpty(permission.code())) {
            return;
        }
        SysUserExt userExt = (SysUserExt) SecurityUtils.getSubject().getPrincipal();
        if (userExt == null) {
            throw new RuntimeException("请先登录");
        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        Map<String, Object> params = new HashMap<>(8);
        String application = request.getHeader(Constants.REQ_HEADER_NAME_APPLICATION);
        if (!HlpUtils.isEmpty(application)) {
            params.put(Constants.PARAMS_KEY_NAME_GROUP_APPLICATION, application);
        }
        SysDataAuthExt authExt = DataPermissionUtil.getSysDataAuth(permission.code(), application, userExt);
        if (authExt == null) {
            return;
        }
        if (SysDataAuthExt.AUTH_MODE_CREATOR.equals(authExt.getAuth_mode())) {
            params.put(Constants.PARAMS_KEY_NAME_CREATOR_SID, userExt.getSid());
        } else if (SysDataAuthExt.AUTH_MODE_GROUP.equals(authExt.getAuth_mode())) {
            List<String> groupList = new ArrayList<>();
            if (!HlpUtils.isEmpty(authExt.getGroup_sid())) {
                groupList.addAll(Arrays.asList(authExt.getGroup_sid().split(",")));
            }
            if (!HlpUtils.isEmpty(userExt.getGroup_sid()) && !groupList.contains(userExt.getGroup_sid())) {
                groupList.add(userExt.getGroup_sid());
            }
            if (!HlpUtils.isEmptyList(groupList)) {
                params.put(Constants.PARAMS_KEY_NAME_GROUP_PERMISSION, groupList);
            }
        }
        request.setAttribute(Constants.REQ_ATTRIBUTE_NAME_PERMISSION_PARAMS, params);
    }
}
